import type { FormInstance } from 'element-plus'
import type { LoopSwitchGroupModalPropsType } from './typings'
import type { LoopSwitchGroupDataItemType } from '../group/typings'
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import { handleTrim } from '~/utils/util'
import { MODAL_SMALL_WIDTH } from '~/utils/const'

export default function LoopSwitchGroupModal(props: LoopSwitchGroupModalPropsType) {
  const { cancel } = props
  const store = useStore()
  const loadingRef = ref<boolean>()
  const ruleFormRef = ref<FormInstance>()
  const formValues = reactive<LoopSwitchGroupDataItemType>({
    id: null,
    ident: 'hardware',
    ...(props?.detail || {})
  })

  // 提交
  const handleSubmit = async () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.validate(async (valid) => {
      if (!valid) return
      loadingRef.value = true

      const params = { ...formValues }
      params.groupName = params.groupName && handleTrim(params.groupName)
      params.sort = params.sort && handleTrim(params.sort)
      const res = await store.dispatch('loopSwitchGroup/UpdateMonitorLoopSwitchGroupInfo', params)
      loadingRef.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        cancel()
      }
    })
  }

  return (
    <ElDialog
      width={MODAL_SMALL_WIDTH}
      title={props?.detail?.id ? '编辑分组' : '新增分组'}
      modelValue={props.visible}
      closeOnClickModal={false} // 点遮罩层不关弹窗
      draggable // 可拖拽
      beforeClose={cancel}
      v-slots={{
        footer: () => (
          <>
            <ElButton type="primary" loading={loadingRef.value} onClick={handleSubmit}>
              保存
            </ElButton>
            <ElButton onClick={cancel}>取消</ElButton>
          </>
        )
      }}
    >
      <ElForm ref={ruleFormRef} model={formValues} labelWidth={100}>
        <ElFormItem
          prop="groupName"
          label="分组名称"
          rules={[{ required: true, min: 3, max: 20, message: '分组名称 3 ~ 20 字符' }]}
        >
          <ElInput
            v-model={formValues.groupName}
            placeholder="请输入分组名称"
            {...{ minlength: 3, maxlength: 20 }}
          />
        </ElFormItem>
        <ElFormItem prop="sort" label="排序" rules={[{ required: false, message: '请输入排序' }]}>
          <ElInput v-model:inputTextareaValue={formValues.sort} placeholder="请输入排序" />
        </ElFormItem>
      </ElForm>
    </ElDialog>
  )
}
